package com.show.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.show.filter.dto.Audience;
import com.show.filter.jwtUtil.JwtHelper;
import com.show.util.ResultMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

public class HTTPBearerAuthorizeAttribute implements Filter {

    @Autowired
    private Audience audienceEntity;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub  
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                filterConfig.getServletContext());

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        ResultMsg resultMsg;
        HttpServletRequest httpRequest = (HttpServletRequest)request;
        Object str = ((HttpServletRequest) request).getSession().getAttribute("token");
        if(str != null){
            String auth = ((HttpServletRequest) request).getSession().getAttribute("token").toString();
            if (JwtHelper.parseJWT(auth, audienceEntity.getBase64Secret()) != null)
            {
                chain.doFilter(request, response);
                return;
            }
        }

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setCharacterEncoding("UTF-8");
        httpResponse.setContentType("application/json; charset=utf-8");
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        ObjectMapper mapper = new ObjectMapper();
        String data="<script >window.location.href='/error'</script>";
        /*获取OutputStream输出流*/
        OutputStream outputStream = response.getOutputStream();
        httpResponse.setHeader("content-type", "text/html;charset=UTF-8");
        byte[] dataByteArr = data.getBytes("UTF-8");
        outputStream.write(dataByteArr);
        return;
    }


    @Override
    public void destroy() {
        // TODO Auto-generated method stub  

    }
}